import { defineStore } from 'pinia';
import { io } from 'socket.io-client';
import { useGameStore } from './game.js';

// 多人游戏配置管理
const MULTIPLAYER_CONFIG = {
  // WebSocket配置
  websocket: {
    reconnectionAttempts: 5,
    reconnectionDelay: 1000,
    timeout: 10000,
    maxRetries: 3,
    baseRetryDelay: 500
  },
  
  // 操作超时配置
  timeouts: {
    operation: 15000,      // 操作超时
    heartbeat: 3000,       // 心跳超时
    gameStateSync: 5000    // 游戏状态同步超时
  },
  
  // 错误处理配置
  errorHandling: {
    enableDetailedLogging: true,
    maxConsecutiveErrors: 5,
    errorRecoveryDelay: 2000
  },
  
  // 性能监控
  performance: {
    enableMetrics: true,
    operationLogThreshold: 2000,
    connectionHealthCheckInterval: 30000
  }
};

const NON_RETRYABLE_ERROR_CODES = new Set([
  'MUST_PLAY',
  'CANNOT_PASS_FIRST',
  'INVALID_PLAY',
  'PLAYER_NOT_FOUND',
  'NOT_YOUR_TURN',
  'GAME_NOT_FOUND',
  'WAITING_COLLECTION',
  'NOT_IN_ROOM',
  'PLAY_FAILED',
  'PASS_FAILED'
]);

export const useMultiplayerStore = defineStore('multiplayer', {
  state: () => ({
    socket: null,
    connected: false,
    connecting: false,
    
    // 玩家和房间信息
    playerId: null,
    playerName: null,
    roomId: null,
    roomData: null,
    
    // 游戏模式
    gameMode: 'single', // 'single' | 'multiplayer'
    
    // 连接状态 - 增强版
    connectionStatus: 'disconnected', // 'connected' | 'connecting' | 'disconnected' | 'error' | 'recovering'
    lastError: null,
    consecutiveErrors: 0,
    lastSuccessfulOperation: Date.now(),
    
    // 游戏状态（多人版）
    multiplayerGameState: null,
    waitingForPlayers: false,
    
    // 性能监控和健康检查
    performanceMetrics: {
      operationTimes: [],
      errorCount: 0,
      reconnectionCount: 0,
      lastHealthCheck: Date.now()
    },
    
    // 连接健康检查
    healthMonitor: {
      enabled: true,
      interval: null,
      lastPing: null,
      consecutiveFailures: 0
    },
    
    // 服务器配置
    serverConfig: {
      wsUrl: 'ws://localhost:3001',
      httpUrl: 'http://localhost:3002'
    }
  }),

  getters: {
    isInRoom: (state) => !!state.roomId,
    isHost: (state) => state.roomData?.hostId === state.playerId,
    playersInRoom: (state) => state.roomData?.players || [],
    canStartGame: (state) => {
      if (!state.roomData || !state.isHost) return false;
      const nonHostPlayers = state.roomData.players.filter(p => p.id !== state.playerId);
      return state.roomData.players.length === 3 && nonHostPlayers.every(p => p.isReady);
    }
  },

  actions: {
    /**
     * 连接到多人游戏服务器 - 增强版
     */
    async connect() {
      if (this.connected || this.connecting) {
        return Promise.resolve();
      }

      return new Promise((resolve, reject) => {
        try {
          this.connecting = true;
          this.connectionStatus = 'connecting';
          this.lastError = null;
          
          // 记录连接尝试
          this.recordPerformanceMetric('connection_attempt');

          this.socket = io(this.serverConfig.wsUrl, {
            reconnection: true,
            reconnectionAttempts: MULTIPLAYER_CONFIG.websocket.reconnectionAttempts,
            reconnectionDelay: MULTIPLAYER_CONFIG.websocket.reconnectionDelay,
            timeout: MULTIPLAYER_CONFIG.websocket.timeout,
            transports: ['websocket', 'polling']
          });

          this.setupSocketListeners();

          // 连接成功 - 增强版
          this.socket.on('connect', () => {
            console.log('WebSocket连接成功');
            this.connected = true;
            this.connecting = false;
            this.connectionStatus = 'connected';
            this.lastError = null;
            this.consecutiveErrors = 0;
            this.lastSuccessfulOperation = Date.now();
            
            // 启动健康监控
            this.startHealthMonitoring();
            
            // 记录成功连接
            this.recordPerformanceMetric('connection_success');
            
            resolve();
          });

          // 连接失败 - 增强错误处理
          this.socket.on('connect_error', (error) => {
            console.error('WebSocket连接失败:', error);
            this.handleConnectionError(error);
            reject(error);
          });

        } catch (error) {
          console.error('创建WebSocket连接失败:', error);
          this.handleConnectionError(error);
          reject(error);
        }
      });
    },

    /**
     * 处理连接错误
     */
    handleConnectionError(error) {
      this.connected = false;
      this.connecting = false;
      this.connectionStatus = 'error';
      this.lastError = error.message;
      this.consecutiveErrors++;
      
      // 记录错误
      this.recordPerformanceMetric('connection_error', {
        error: error.message,
        consecutiveErrors: this.consecutiveErrors
      });
      
      // 检查是否需要错误恢复
      if (this.consecutiveErrors >= MULTIPLAYER_CONFIG.errorHandling.maxConsecutiveErrors) {
        this.triggerErrorRecovery('connection_failure', {
          consecutiveErrors: this.consecutiveErrors,
          lastError: error.message
        });
      }
    },

    /**
     * 设置WebSocket事件监听器 - 增强版
     */
    setupSocketListeners() {
      if (!this.socket) return;

      // 断开连接 - 增强处理
      this.socket.on('disconnect', (reason) => {
        console.log('WebSocket连接断开:', reason);
        this.connected = false;
        this.connectionStatus = 'disconnected';
        
        // 停止健康监控
        this.stopHealthMonitoring();
        
        // 记录断开原因
        this.recordPerformanceMetric('disconnection', { reason });
        
        if (reason === 'io server disconnect') {
          // 服务器主动断开，延迟重连避免冲突
          console.log('服务器断开连接，延迟重连');
          setTimeout(() => {
            if (!this.connected && this.shouldAttemptReconnection()) {
              this.socket.connect();
            }
          }, MULTIPLAYER_CONFIG.errorHandling.errorRecoveryDelay);
        } else {
          // 其他原因，立即重连
          if (this.shouldAttemptReconnection()) {
            this.socket.connect();
          }
        }
        
        // 通知游戏Store连接状态变化
        this.notifyConnectionChange('disconnected', { reason });
      });

      // 重连成功 - 增强处理
      this.socket.on('reconnect', (attemptNumber) => {
        console.log(`WebSocket重连成功（第${attemptNumber}次尝试）`);
        this.connected = true;
        this.connectionStatus = 'connected';
        this.lastError = null;
        this.consecutiveErrors = 0;
        this.lastSuccessfulOperation = Date.now();
        
        // 记录重连
        this.performanceMetrics.reconnectionCount++;
        this.recordPerformanceMetric('reconnection_success', { attemptNumber });
        
        // 重启健康监控
        this.startHealthMonitoring();

        // 如果有房间信息，重新注册
        if (this.playerId && this.roomId) {
          this.registerPlayer().catch(error => {
            console.error('重连后注册玩家失败:', error);
          });
        }
      });

      // 房间相关事件
      this.socket.on('room_created', this.handleRoomCreated.bind(this));
      this.socket.on('room_joined', this.handleRoomJoined.bind(this));
      this.socket.on('player_joined', this.handlePlayerJoined.bind(this));
      this.socket.on('player_left', this.handlePlayerLeft.bind(this));
      this.socket.on('room_updated', this.handleRoomUpdated.bind(this));
      this.socket.on('player_disconnected', this.handlePlayerDisconnected.bind(this));

      // 游戏相关事件
      this.socket.on('game_started', this.handleGameStarted.bind(this));
      this.socket.on('game_state_update', this.handleGameStateUpdate.bind(this));
      this.socket.on('game_state_restored', this.handleGameStateRestored.bind(this));

      // 错误事件 - 增强处理
      this.socket.on('error', (error) => {
        console.error('WebSocket错误:', error);
        this.lastError = error.message;
        this.consecutiveErrors++;
        
        // 记录错误
        this.recordPerformanceMetric('websocket_error', {
          error: error.message,
          consecutiveErrors: this.consecutiveErrors
        });
      });
    },

    /**
     * 判断是否应该尝试重连
     */
    shouldAttemptReconnection() {
      // 检查连续错误次数
      if (this.consecutiveErrors >= MULTIPLAYER_CONFIG.errorHandling.maxConsecutiveErrors) {
        console.warn('连续错误次数过多，禁止自动重连');
        return false;
      }
      
      // 检查游戏状态
      if (!this.roomId && !this.playerId) {
        console.log('无房间信息，不需重连');
        return false;
      }
      
      return true;
    },

    /**
     * 启动健康监控
     */
    startHealthMonitoring() {
      if (!this.healthMonitor.enabled || this.healthMonitor.interval) {
        return;
      }
      
      console.debug('启动连接健康监控');
      
      this.healthMonitor.interval = setInterval(() => {
        this.performHealthCheck();
      }, MULTIPLAYER_CONFIG.performance.connectionHealthCheckInterval);
    },

    /**
     * 停止健康监控
     */
    stopHealthMonitoring() {
      if (this.healthMonitor.interval) {
        clearInterval(this.healthMonitor.interval);
        this.healthMonitor.interval = null;
        console.debug('停止连接健康监控');
      }
    },

    /**
     * 执行健康检查
     */
    async performHealthCheck() {
      if (!this.connected || !this.socket) {
        return;
      }
      
      try {
        const startTime = Date.now();
        await this.pingServer();
        const responseTime = Date.now() - startTime;
        
        // 重置失败计数
        this.healthMonitor.consecutiveFailures = 0;
        this.performanceMetrics.lastHealthCheck = Date.now();
        
        // 记录性能指标
        this.recordPerformanceMetric('health_check_success', { responseTime });
        
        if (responseTime > MULTIPLAYER_CONFIG.performance.operationLogThreshold) {
          console.warn(`健康检查响应过慢: ${responseTime}ms`);
        }
        
      } catch (error) {
        this.healthMonitor.consecutiveFailures++;
        console.error('健康检查失败:', error);
        
        // 记录失败
        this.recordPerformanceMetric('health_check_failure', {
          error: error.message,
          consecutiveFailures: this.healthMonitor.consecutiveFailures
        });
        
        // 如果连续失败过多，触发连接问题处理
        if (this.healthMonitor.consecutiveFailures >= 3) {
          console.warn('连续健康检查失败，可能存在连接问题');
          this.connectionStatus = 'unstable';
        }
      }
    },

    /**
     * 设置WebSocket事件监听器
     */
    setupEventListeners() {
      if (!this.socket) return;

      this.socket.on('room_created', this.handleRoomCreated.bind(this));
      this.socket.on('room_joined', this.handleRoomJoined.bind(this));
      this.socket.on('player_joined', this.handlePlayerJoined.bind(this));
      this.socket.on('player_left', this.handlePlayerLeft.bind(this));
      this.socket.on('room_updated', this.handleRoomUpdated.bind(this));
      this.socket.on('player_disconnected', this.handlePlayerDisconnected.bind(this));

      // 游戏相关事件
      this.socket.on('game_started', this.handleGameStarted.bind(this));
      this.socket.on('game_state_update', this.handleGameStateUpdate.bind(this));
      this.socket.on('game_state_restored', this.handleGameStateRestored.bind(this));

      // 错误事件
      this.socket.on('error', (error) => {
        console.error('WebSocket错误:', error);
        this.lastError = error.message;
      });
    },

    /**
     * 注册玩家
     */
    async registerPlayer() {
      if (!this.socket || !this.connected) {
        throw new Error('未连接到服务器');
      }

      return new Promise((resolve, reject) => {
        this.socket.emit('register_player', {
          playerId: this.playerId,
          roomId: this.roomId
        }, (response) => {
          if (response.success) {
            resolve(response);
          } else {
            reject(new Error(response.error?.message || '注册失败'));
          }
        });
      });
    },

    /**
     * 创建房间
     */
    async createRoom(roomName, playerName) {
      if (!this.socket || !this.connected) {
        throw new Error('未连接到服务器');
      }

      return new Promise((resolve, reject) => {
        this.socket.emit('create_room', {
          roomName,
          playerName
        }, (response) => {
          if (response.success) {
            const { room, player } = response.data;
            this.playerId = player.id;
            this.playerName = player.name;
            this.roomId = room.id;
            this.roomData = room;
            this.gameMode = 'multiplayer';
            
            // 注册玩家
            this.registerPlayer().catch(console.error);
            
            resolve(response);
          } else {
            reject(new Error(response.error?.message || '创建房间失败'));
          }
        });
      });
    },

    /**
     * 加入房间
     */
    async joinRoom(roomId, playerName) {
      if (!this.socket || !this.connected) {
        throw new Error('未连接到服务器');
      }

      return new Promise((resolve, reject) => {
        this.socket.emit('join_room', {
          roomId,
          playerName
        }, (response) => {
          if (response.success) {
            const { room, player } = response.data;
            this.playerId = player.id;
            this.playerName = player.name;
            this.roomId = room.id;
            this.roomData = room;
            this.gameMode = 'multiplayer';
            
            // 注册玩家
            this.registerPlayer().catch(console.error);
            
            resolve(response);
          } else {
            reject(new Error(response.error?.message || '加入房间失败'));
          }
        });
      });
    },

    /**
     * 离开房间
     */
    async leaveRoom() {
      if (!this.socket || !this.connected) {
        return { success: false, message: '未连接到服务器' };
      }

      return new Promise((resolve, reject) => {
        this.socket.emit('leave_room', (response) => {
          if (response.success) {
            this.clearRoomData();
            resolve(response);
          } else {
            reject(new Error(response.error?.message || '离开房间失败'));
          }
        });
      });
    },

    /**
     * 切换准备状态
     */
    async toggleReady(ready) {
      if (!this.socket || !this.connected || !this.roomId) {
        throw new Error('未连接到服务器或未在房间中');
      }

      return new Promise((resolve, reject) => {
        this.socket.emit('toggle_ready', { ready }, (response) => {
          if (response.success) {
            resolve(response);
          } else {
            reject(new Error(response.error?.message || '操作失败'));
          }
        });
      });
    },

    /**
     * 开始游戏
     */
    async startGame() {
      if (!this.socket || !this.connected || !this.roomId) {
        throw new Error('未连接到服务器或未在房间中');
      }

      return new Promise((resolve, reject) => {
        this.socket.emit('start_game', (response) => {
          if (response.success) {
            resolve(response);
          } else {
            reject(new Error(response.error?.message || '开始游戏失败'));
          }
        });
      });
    },

    /**
     * 添加AI玩家补位
     */
    async addAIPlayer() {
      if (!this.socket || !this.connected || !this.roomId) {
        throw new Error('未连接到服务器或未在房间中');
      }

      return new Promise((resolve, reject) => {
        this.socket.emit('add_ai_player', (response) => {
          if (response.success) {
            // 更新房间数据
            this.roomData = response.data.room;
            resolve(response);
          } else {
            reject(new Error(response.error?.message || '添加AI玩家失败'));
          }
        });
      });
    },

    /**
     * 获取房间列表
     */
    async getRoomList() {
      try {
        const response = await fetch(`${this.serverConfig.httpUrl}/api/rooms`);
        const result = await response.json();
        return result;
      } catch (error) {
        console.error('获取房间列表失败:', error);
        return { success: false, message: '获取房间列表失败' };
      }
    },

    /**
     * 游戏操作 - 出牌（增强AI操作支持）
     */
    async playCards(cards, playerId = null) {
      return this.safeSocketOperation('出牌', async () => {
        // 序列化卡牌对象为简单JSON对象
        const serializedCards = Array.isArray(cards)
          ? cards.map(card => card.toJSON ? card.toJSON() : card)
          : [];

        const payload = playerId
          ? { cards: serializedCards, playerId }
          : { cards: serializedCards };

        console.log('[出牌] 发送数据:', payload);
        return this.safeGameOperation('play_cards', payload, '出牌操作');
      });
    },

    /**
     * 游戏操作 - 扣牌（增强AI操作支持）
     */
    async passTurn(discardCards, playerId = null) {
      return this.safeSocketOperation('扣牌', async () => {
        // 序列化卡牌对象为简单JSON对象
        const serializedCards = Array.isArray(discardCards)
          ? discardCards.map(card => card.toJSON ? card.toJSON() : card)
          : [];

        const payload = playerId
          ? { discardCards: serializedCards, playerId }
          : { discardCards: serializedCards };

        console.log('[扣牌] 发送数据:', payload);
        return this.safeGameOperation('pass_turn', payload, '扣牌操作');
      });
    },

    /**
     * 游戏操作 - 收牌（增强AI操作支持）
     */
    async collectCards() {
      return this.safeGameOperation('collect_cards', {}, '收牌操作');
    },

    /**
     * 安全的游戏操作包装器
     */
    async safeGameOperation(eventName, data = {}, operationName = '游戏操作') {
      if (!this.socket || !this.connected) {
        throw new Error('未连接到服务器');
      }

      const maxRetries = 3;
      const baseDelay = 500;
      const maxTimeout = 15000; // 15秒超时

      for (let attempt = 1; attempt <= maxRetries; attempt++) {
        try {
          console.log(`执行${operationName}，尝试 ${attempt}/${maxRetries}`);
          
          const result = await Promise.race([
            this.executeGameOperation(eventName, data),
            this.createTimeoutPromise(maxTimeout, `${operationName}超时`)
          ]);
          
          if (result && result.success) {
            console.log(`${operationName}成功:`, result);
            return result;
          } else {
            const errorCode = result?.error?.code;
            const errorMessage = result?.error?.message || `${operationName}失败`;
            const nonRetryable = errorCode && NON_RETRYABLE_ERROR_CODES.has(errorCode);
            const err = new Error(errorMessage);
            if (errorCode) {
              err.code = errorCode;
            }
            if (nonRetryable) {
              err.nonRetryable = true;
            }
            throw err;
          }
          
        } catch (error) {
          console.error(`${operationName}失败 (尝试 ${attempt}/${maxRetries}):`, error);
          
          const shouldRetry = !(error.nonRetryable || (error.code && NON_RETRYABLE_ERROR_CODES.has(error.code)));
          
          if (!shouldRetry) {
            throw error;
          }

          if (attempt === maxRetries) {
            // 最后一次尝试失败
            throw error;
          }
          
          // 检查连接健康状态
          await this.ensureConnectionHealth();
          
          // 指数退防延迟
          const delay = baseDelay * Math.pow(2, attempt - 1);
          await new Promise(resolve => setTimeout(resolve, delay));
        }
      }
    },

    /**
     * 执行游戏操作
     */
    executeGameOperation(eventName, data) {
      return new Promise((resolve, reject) => {
        const timeoutId = setTimeout(() => {
          reject(new Error('服务器响应超时'));
        }, 10000);
        
        this.socket.emit(eventName, data, (response) => {
          clearTimeout(timeoutId);
          resolve(response);
        });
      });
    },

    /**
     * 创建超时Promise
     */
    createTimeoutPromise(timeout, message) {
      return new Promise((_, reject) => {
        setTimeout(() => reject(new Error(message)), timeout);
      });
    },

    /**
     * 确保连接健康
     */
    async ensureConnectionHealth() {
      if (!this.connected || !this.socket) {
        console.log('连接异常，尝试重连...');
        try {
          await this.connect();
          
          // 重新注册玩家（如果有房间信息）
          if (this.playerId && this.roomId) {
            await this.registerPlayer();
          }
        } catch (error) {
          console.error('重连失败:', error);
          throw error;
        }
      } else {
        // 发送心跳检查连接
        try {
          await this.pingServer();
        } catch (error) {
          console.warn('心跳检查失败:', error);
          // 心跳失败不直接抛出异常，给后续操作机会
        }
      }
    },

    /**
     * Ping服务器检查连接
     */
    async pingServer() {
      if (!this.socket || !this.connected) {
        throw new Error('连接不可用');
      }

      return new Promise((resolve, reject) => {
        const timeout = setTimeout(() => {
          reject(new Error('Ping超时'));
        }, 3000);

        this.socket.emit('ping', (response) => {
          clearTimeout(timeout);
          if (response && response.success) {
            resolve(response);
          } else {
            reject(new Error('Ping失败'));
          }
        });
      });
    },

    /**
     * 游戏操作 - 发起扣了（增强版）
     */
    async initiateKouLe() {
      return this.safeGameOperation('initiate_koule', {}, '发起扣了操作');
    },

    /**
     * 游戏操作 - 响应扣了（增强版）
     */
    async respondKouLe(decision) {
      return this.safeGameOperation('respond_koule', { decision }, '响应扣了操作');
    },

    // 事件处理器
    handleRoomCreated(data) {
      console.log('房间创建事件:', data);
      if (data.success && data.data) {
        this.roomData = data.data.room;
      }
    },

    handleRoomJoined(data) {
      console.log('加入房间事件:', data);
      if (data.success && data.data) {
        this.roomData = data.data.room;
      }
    },

    handlePlayerJoined(data) {
      console.log('玩家加入事件:', data);
      if (data.success && data.data) {
        this.roomData = data.data.room;
      }
    },

    handlePlayerLeft(data) {
      console.log('玩家离开事件:', data);
      if (data.success && data.data) {
        this.roomData = data.data.room;
      }
    },

    handleRoomUpdated(data) {
      console.log('房间更新事件:', data);
      if (data.success && data.data) {
        this.roomData = data.data;
      }
    },

    handlePlayerDisconnected(data) {
      console.log('玩家断开连接事件:', data);
      // 可以显示玩家离线提示
    },

    handleGameStarted(data) {
      console.log('游戏开始事件原始数据:', data);
      
      try {
        // 数据结构验证
        if (!data) {
          throw new Error('游戏开始事件数据为空');
        }
        
        if (!data.success) {
          throw new Error(data.error?.message || '游戏开始失败');
        }
        
        if (!data.data) {
          throw new Error('游戏开始事件缺少data字段');
        }
        
      // 兼容两种返回结构：
      // 1) { data: { sessionId, gameState: {...} } }
      // 2) { data: { ...gameState } }
      const payload = data.data;
      const gameData = payload?.gameState || payload;
      if (!gameData || !Array.isArray(gameData.players)) {
        console.error('玩家数据无效:', payload);
        throw new Error('服务器返回的玩家数据无效');
      }
        
        console.log('验证通过，玩家数量:', gameData.players.length);
        
      this.multiplayerGameState = gameData;
        
        // 触发游戏状态切换
        const gameStore = useGameStore();
        if (gameStore) {
          // 将当前玩家ID添加到游戏状态中
          const enhancedGameState = {
            ...gameData,
            currentPlayerId: this.playerId
          };
          
          console.log('增强的游戏状态:', enhancedGameState);
          
          gameStore.initMultiplayerGame(enhancedGameState);
        } else {
          throw new Error('游戏Store未初始化');
        }
      } catch (error) {
        console.error('处理游戏开始事件失败:', error);
        
        // 用户友好的错误处理
        this.lastError = error.message;
        this.connectionStatus = 'error';
        
        // 可选：自动尝试重连或返回lobby
        this.handleGameStartError(error);
      }
    },

    /**
     * 处理游戏开始错误
     */
    handleGameStartError(error) {
      console.error('游戏开始失败:', error);
      
      // 清理游戏状态
      this.multiplayerGameState = null;
      
      // 通知用户
      // 这里可以触发全局通知组件
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('multiplayer-error', {
          detail: {
            type: 'game_start_failed',
            message: error.message,
            action: 'return_to_lobby'
          }
        }));
      }
    },

    /**
     * 处理游戏初始化错误（由game store调用）
     */
    handleGameInitError(error) {
      console.error('游戏初始化失败:', error);
      
      // 清理相关状态
      this.multiplayerGameState = null;
      this.connectionStatus = 'error';
      this.lastError = error.message;
    },

    handleGameStateUpdate(data) {
      console.log('游戏状态更新事件:', data);
      if (data && data.success && data.data) {
        // 兼容两种结构：{data: {gameState}} 和 {data: gameState}
        const gameState = data.data.gameState || data.data;
        this.multiplayerGameState = gameState;
        
        // 同步到游戏 store并检查AI回合
        this.syncToGameStore(gameState);
      }
    },

    handleGameStateRestored(data) {
      console.log('游戏状态恢复事件:', data);
      if (data && data.success && data.data) {
        // 恢复事件通常直接返回 gameState，但也兼容带 gameState 包装
        const gameState = data.data.gameState || data.data;
        this.multiplayerGameState = gameState;
        
        // 同步到游戏 store并检查AI回合
        this.syncToGameStore(gameState);
      }
    },

    /**
     * 清理房间数据
     */
    clearRoomData() {
      this.playerId = null;
      this.playerName = null;
      this.roomId = null;
      this.roomData = null;
      this.multiplayerGameState = null;
      this.gameMode = 'single';
      this.waitingForPlayers = false;
    },

    /**
     * 断开连接
     */
    /**
     * 断开连接 - 增强版
     */
    disconnect() {
      // 停止健康监控
      this.stopHealthMonitoring();
      
      if (this.socket) {
        this.socket.disconnect();
        this.socket = null;
      }
      this.connected = false;
      this.connecting = false;
      this.connectionStatus = 'disconnected';
      this.clearRoomData();
      
      // 记录断开连接
      this.recordPerformanceMetric('manual_disconnect');
    },

    /**
     * 发送心跳（增强版）
     */
    sendHeartbeat() {
      if (this.socket && this.connected) {
        this.pingServer().then(response => {
          console.debug('心跳响应:', response);
        }).catch(error => {
          console.warn('心跳失败:', error);
          // 心跳失败可能预示连接问题
          this.connectionStatus = 'unstable';
        });
      }
    },

    /**
     * 获取当前玩家的手牌
     */
    getPersonalCards(playerId) {
      if (!this.multiplayerGameState?.personalCards) return [];
      return this.multiplayerGameState.personalCards[playerId] || [];
    },

    /**
     * 获取多人游戏的玩家列表（用于UI显示）
     */
    getMultiplayerPlayers() {
      if (!this.multiplayerGameState?.players) return [];
      return this.multiplayerGameState.players;
    },

    /**
     * 同步多人游戏状态到游戏界面
     */
    syncToGameStore(gameState) {
      const gameStore = useGameStore();
      if (gameStore && this.gameMode === 'multiplayer') {
        gameStore.syncMultiplayerState(gameState);
      }
    },

    /**
     * 通知连接状态变化
     */
    /**
     * 通知连接状态变化 - 增强版
     */
    notifyConnectionChange(status, data = {}) {
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('multiplayer-connection-change', {
          detail: { 
            status, 
            timestamp: Date.now(),
            playerId: this.playerId,
            consecutiveErrors: this.consecutiveErrors,
            lastSuccessfulOperation: this.lastSuccessfulOperation,
            ...data
          }
        }));
      }
    },

    // ========== 性能监控和错误处理 ==========

    /**
     * 记录性能指标
     */
    recordPerformanceMetric(type, data = {}) {
      if (!MULTIPLAYER_CONFIG.performance.enableMetrics) return;
      
      const metric = {
        type,
        data,
        timestamp: Date.now()
      };
      
      // 根据类型处理
      switch (type) {
        case 'operation_success':
        case 'operation_failure':
          this.performanceMetrics.operationTimes.push(metric);
          // 保持最近100条记录
          if (this.performanceMetrics.operationTimes.length > 100) {
            this.performanceMetrics.operationTimes.shift();
          }
          
          // 性能警告
          if (data.duration > MULTIPLAYER_CONFIG.performance.operationLogThreshold) {
            console.warn(`${data.operationName}操作时间过长: ${data.duration}ms`);
          }
          break;
          
        case 'connection_error':
        case 'websocket_error':
          this.performanceMetrics.errorCount++;
          break;
          
        default:
          console.debug('性能指标记录:', metric);
      }
    },

    /**
     * 触发错误恢复机制
     */
    triggerErrorRecovery(errorType, data) {
      console.warn(`触发错误恢复: ${errorType}`, data);
      
      this.connectionStatus = 'recovering';
      
      // 发送错误恢复事件
      if (typeof window !== 'undefined') {
        window.dispatchEvent(new CustomEvent('multiplayer-error-recovery', {
          detail: {
            type: errorType,
            data,
            timestamp: Date.now()
          }
        }));
      }
      
      // 根据错误类型执行恢复策略
      setTimeout(() => {
        switch (errorType) {
          case 'connection_failure':
            this.handleConnectionFailureRecovery();
            break;
            
          default:
            console.warn(`未知错误类型: ${errorType}`);
        }
      }, MULTIPLAYER_CONFIG.errorHandling.errorRecoveryDelay);
    },

    /**
     * 处理连接失败恢复
     */
    async handleConnectionFailureRecovery() {
      console.log('开始连接失败恢复流程');
      
      try {
        // 重置错误计数
        this.consecutiveErrors = 0;
        
        // 尝试重新连接
        await this.connect();
        
        // 恢复成功
        this.connectionStatus = 'connected';
        console.log('连接恢复成功');
        
      } catch (error) {
        console.error('连接恢复失败:', error);
        this.connectionStatus = 'error';
        
        // 可以考虑显示用户友好的错误提示
      }
    },

    /**
     * 获取性能统计信息
     */
    getPerformanceStats() {
      if (!MULTIPLAYER_CONFIG.performance.enableMetrics) {
        return null;
      }
      
      const recentOperations = this.performanceMetrics.operationTimes.slice(-20);
      const avgOperationTime = recentOperations.length > 0 
        ? recentOperations.reduce((sum, op) => sum + (op.data.duration || 0), 0) / recentOperations.length
        : 0;
      
      return {
        totalOperations: this.performanceMetrics.operationTimes.length,
        recentAverageTime: Math.round(avgOperationTime),
        errorCount: this.performanceMetrics.errorCount,
        reconnectionCount: this.performanceMetrics.reconnectionCount,
        consecutiveErrors: this.consecutiveErrors,
        lastHealthCheck: this.performanceMetrics.lastHealthCheck,
        uptime: Date.now() - (this.lastSuccessfulOperation || Date.now())
      };
    },

    /**
     * 增强的WebSocket操作包装器
     */
    async safeSocketOperation(operationName, operation) {
      const maxRetries = 3;
      let attempt = 0;
      
      while (attempt < maxRetries) {
        try {
          if (!this.connected) {
            console.log(`${operationName}: 连接已断开，尝试重连`);
            await this.connect();
          }
          
          const result = await operation();
          return result;
          
        } catch (error) {
          attempt++;
          console.error(`${operationName} 第${attempt}次尝试失败:`, error);
          
          if (attempt >= maxRetries) {
            throw new Error(`${operationName} 在${maxRetries}次尝试后仍然失败: ${error.message}`);
          }
          
          // 重试前等待
          await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
        }
      }
      
      throw new Error(`${operationName} 最大重试次数已达到`);
    }
  }
});
